package controller

import (
	. "TaylorTest/app"
	. "TaylorTest/model"
	"encoding/json"
	"fmt"
	"net/http"
)

//登录
func Login(context *Context) {
	context.Request.ParseForm()
	username := context.Request.Form["username"][0]
	password := context.Request.Form["password"][0]
	if username != "" || password != "" {
		user := getUser(username, password)
		if user != nil {
			http.SetCookie(context.ResponseWriter, &http.Cookie{
				Name:     "token",
				Value:    username,
				MaxAge:   3600,
				Path:     "",
				Domain:   "",
				Secure:   false,
				HttpOnly: true,
			})
			http.Redirect(context.ResponseWriter, context.Request, "/static/periodlist.html", 301)
		} else {
			fmt.Fprintf(context.ResponseWriter, "用户名或密码不正确")
		}
	} else {
		fmt.Fprintf(context.ResponseWriter, "请输入用户名和密码")
	}
}

//登出
func Logout(context *Context) {
	cookie := http.Cookie{Name: "token", Path: "/", MaxAge: -1}
	http.SetCookie(context.ResponseWriter, &cookie)
	http.Redirect(context.ResponseWriter, context.Request, "/logout", 302)
}

//从/appdata/users.json获取用户数据
func getUsers() []User {
	filtBytes := FileReadAll("/appdata/users.json")
	res := &[]User{}
	json.Unmarshal(filtBytes, &res)
	return *res
}

//获取单个用户
func getUser(username string, password string) *User {
	users := getUsers()
	for i := 0; i < len(users)-1; i++ {
		if users[i].UserName == username && users[i].Password == password {
			return &users[i]
		}
	}
	return nil
}
